package com.chorye.elastic.controller;

import com.chorye.elastic.entity.Student;
import com.chorye.elastic.service.StudentService;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Company: 北京根网科技有限公司
 * @Author JiangYy
 * @Title: StudentController
 * @Description: TODO
 * @Date 2019/1/10 14:01
 */
@RestController
@RequestMapping("/elastic")
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 通过rest方式访问
     *
     * @param id 学生id
     */
    @RequestMapping("/rest/{id}")
    public Student rest(@PathVariable Integer id) throws IOException {
        // 创建restTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 存放请求参数集合
        Map<String, Object> params = new HashMap<>(1);
        params.put("id", id);
        // 发送请求
        String object = restTemplate.getForObject("http://127.0.0.1:9200/school/student/{id}", String.class, params);
        if (object != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonFactory jsonFactory = new JsonFactory();
            // 创建解析器
            JsonParser jsonParser = jsonFactory.createParser(object);
            // 获取root节点
            JsonNode rootNode = objectMapper.readTree(jsonParser);
            // 只对json字段中的source感兴趣
            JsonNode sourceNode = rootNode.get("_source");
            // 将source字段的文档部分映射到Student对象
            return objectMapper.convertValue(sourceNode, Student.class);
        }
        return null;
    }

    /**
     * 通过SpringDataElastic访问
     *
     * @param id 学生id
     */
    @RequestMapping("/data/{id}")
    public Student get(@PathVariable Integer id) {
        return studentService.get(id);
    }

    /**
     * 查询所有学生
     *
     * @return 所有学生
     */
    @RequestMapping("/data/list")
    public List<Student> list() {
        return studentService.selectAll();
    }

    /**
     * 保存学生
     *
     * @return 成功返回的实体
     */
    @RequestMapping("/data/save")
    public Student save() {
        return studentService.save();
    }

    /**
     * 修改学生
     *
     * @return 成功返回的实体
     */
    @RequestMapping("/data/update")
    public Student update() {
        return studentService.update();
    }

    /**
     * 通过id删除学生
     */
    @RequestMapping("/data/delete")
    public void delete() {
        studentService.delete(1);
        studentService.remove("NoSql修改测试");
    }
}
